/*
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-04-18 14:07:27
 * @LastEditTime: 2021-05-27 22:14:34
 * @LastEditors: zheng yiliang
 */

var express = require('express');
var router = express.Router();
const { SuccessModel, ErrorModel } = require('../util')
const { Tag } = require('../model')
const { PUBLIC_ERROR_MSG } = require('../core/constant');
const loginCheck = require('../middleware/loginCheck');

// 分类列表
router.get('/list', loginCheck, async (req, res) => {
  const { pagenum, pagesize, keyword, dateRange } = req.query
  const pageNum = pagenum * 1 || 1
  const pageSize = pagesize * 1 || 5
  let conditions = {}
  if (keyword) {
    const reg = new RegExp(keyword, 'i')
    conditions = {
      $or: [{ name: { $regex: eval(reg) } }, { desc: { $regex: eval(reg) } }]
    }
  }
  if (dateRange) conditions.create_time = {
    "$gte": new Date(`${dateRange[0]} 00:00:00`),
    "$lte": new Date(`${dateRange[1]} 23:59:59`)
  }

  const skip = pageNum - 1 < 0 ? 0 : (pageNum - 1) * pageSize
  const responseData = {
    count: 0,
    list: []
  }

  Tag.countDocuments(conditions, (err, count) => {
    if (err) {
      res.json(new ErrorModel(err, PUBLIC_ERROR_MSG))
    } else {
      responseData.count = count
      let fields = { name: 1, desc: 1, create_time: 1 } // 待返回的字段
      let options = {
        skip: skip,
        limit: pageSize,
        sort: { create_time: -1 }
      }
      Tag.find(conditions, fields, options, (error, result) => {
        if (err) {
          res.json(new ErrorModel(err, PUBLIC_ERROR_MSG))
        } else {
          responseData.list = result;
          res.json(new SuccessModel(responseData, '分类列表获取成功'))
        }
      })
    }
  })
})
// 新增分类
router.post('/add', loginCheck, async (req, res) => {
  const { name, desc } = req.body;
  Tag.findOne({
    name,
  })
    .then(result => {
      if (!result) {
        const category = new Tag({
          name,
          desc,
        });
        category
          .save()
          .then(data => {
            res.json(new SuccessModel('添加成功'))
          })
          .catch(err => {
            throw err;
          });
      } else {
        res.json(new ErrorModel('该分类已存在'))
      }
    })
    .catch(err => {
      res.json(new ErrorModel(err, PUBLIC_ERROR_MSG))
    });
})
// 分类详情
router.get('/detail', loginCheck, async (req, res) => {
  const { id } = req.query;
  const result = await Tag.findById(id)
  res.json(new SuccessModel(result, '分类详情获取成功'))
})


// 编辑分类
router.put('/edit', loginCheck, async (req, res) => {
  const { _id, name, desc } = req.body;
  // Tag.findOne({
  //   name,
  // })
  //   .then(result => {
  //     if (!result) {
  Tag.findByIdAndUpdate(_id, { name, desc })
    .then(data => {
      res.json(new SuccessModel('修改成功'))
    })
    .catch(err => {
      throw err;
    });
  //   } else {
  //     res.json(new ErrorModel('该分类已存在'))
  //   }
  // })
  // .catch(err => {
  //   res.json(new ErrorModel(err, PUBLIC_ERROR_MSG))
  // });
})
// 删除分类
router.delete('/del', loginCheck, async (req, res) => {
  let { id } = req.body;
  Tag.findByIdAndDelete(id)
    .then(result => {
      if (result) {
        res.json(new SuccessModel('删除成功！'))
      } else {
        res.json(new ErrorModel('分类不存在'))
      }
    })
    .catch(err => {
      res.json(new ErrorModel(err, '分类不存在'))

    });
})

module.exports = router;
